package com.example.service.impl;

import com.example.config.CosConfig;
import com.example.domain.ResponseResult;
import com.example.domain.enums.FileTypeEnum;
import com.example.domain.vo.FileVo;
import com.example.exception.SystemException;
import com.example.service.FileService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.example.domain.enums.AppHttpCodeEnum.FILE_TYPE_ERROR;

/**
 * @author hlc
 * @version 1.0
 * @date 2022/10/12 9:05
 */
@Service
public class FileServiceImpl implements FileService {
    private final CosConfig cosConfig;

    public FileServiceImpl(CosConfig cosConfig) {
        this.cosConfig = cosConfig;
    }

    @Override
    public ResponseResult<FileVo> uploadImage(MultipartFile file) {
        if (!FileTypeEnum.JPEG.getType().equals(file.getContentType()) && !FileTypeEnum.JPEG.getType().equals(file.getContentType())) {
            throw new SystemException(FILE_TYPE_ERROR);
        }
        String[] type = Objects.requireNonNull(file.getContentType()).split("/");
        String prefix = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = prefix + UUID.randomUUID() + "." + type[type.length - 1];
        upload(file, key);
        return ResponseResult.okResult(new FileVo(cosConfig.getBaseUrl() + key));
    }

    @SneakyThrows
    private void upload(MultipartFile file, String filePath) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                cosConfig.getBucketName(),
                filePath,
                file.getInputStream(),
                objectMetadata
        );
        COSCredentials cosCredentials = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
        Region region = new Region(cosConfig.getRegionName());
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = new COSClient(cosCredentials, clientConfig);
        cosClient.putObject(putObjectRequest);
    }
}
